﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace zTalk.Network
{
    public class Json
    {
        public static string Encode<T>(T obj)
        {
            DataContractJsonSerializer serializer = 
                new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, obj);

            return Encoding.UTF8.GetString(ms.ToArray());
        }

        public static T Decode<T>(string json)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer serializer = 
                new DataContractJsonSerializer(typeof(T));
            T obj = (T)serializer.ReadObject(ms);
            ms.Close();

            return obj;
        }
    }
}
